<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\api\controller\Goeasy;
/**
*
* example目录下为简单的支付样例，仅能用于搭建快速体验微信支付使用
* 样例的作用仅限于指导如何使用sdk，在安全上面仅做了简单处理， 复制使用样例代码时请慎重
* 请勿直接直接使用样例对外提供服务
* 
**/

// require_once "../lib/WxPay.Api.php";
// require_once '../lib/WxPay.Notify.php';
// require_once "WxPay.Config.php";


class Vxnotify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);

		$config = new WxPayConfig();
		$result = WxPayApi::orderQuery($config, $input);
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}
	
	public function index(){
	    
        include_once realpath(__DIR__ ."/../../../addons/vxpay/lib/WxPay.Api.php");
        include_once realpath(__DIR__ ."/../../../addons/vxpay/lib/WxPay.Notify.php");
        include_once realpath(__DIR__ ."/../../../addons/vxpay/example/WxPay.Config.php");
        
        $config = new \WxPayConfig();
        $notify = new \WxPayNotify();
        $data = $notify->Handle($config, false);
		echo 'success';
	}
	
	public function alipay_notify(){
	    $data = $_POST;
	    error_log("data=post".json_encode($data),3,'alipay_notify.log');
	    $sign = $data['sign'];
	    $check_data = base64_decode($sign);
	    $trade_status = $data['trade_status'];
	    if($trade_status == 'TRADE_SUCCESS'){
	        $out_trade_no = $data['out_trade_no'];
	        
	        $type = '支付宝';
    		if($out_trade_no[0] == "I"){
    		    //商城订单
    		    $reorder = Db::name('reorder')->where('order_sn',$out_trade_no)->find();
    		    if($reorder['status'] != 1){
        		    echo 'SUCCESS';die;
        		}
	            error_log(date("Y-m-d H:i:s",time())."支付宝商城支付",3,'alipay_notify.log');
                $user = Db::name('personal')->where('id',$reorder['buyid'])->value('switch');
    		    if ($user == 2) {
                    $ret1 = [
                        'uid'   =>  $reorder['buyid'],
                        'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                        'money' =>  '-'.$reorder['prices'],
                        'type'  =>  1,
                        'content'   =>  '收货订单交易',
                        'createtime'    =>  time(),
                        'arrivaltime'   =>  time(),
                        'status'    =>  1
                    ];
                    $re['s1'] = Db::name('reorder')->where('order_sn',$out_trade_no)->update(['status'=>30,'paytime'=>time(),'payway'=>$type]);
                    $re['s2'] = Db::name('account_log')->insert($ret1);
                } else {
                    $ret1 = [
                        'uid'   =>  $reorder['buyid'],
                        'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                        'money' =>  '-'.$reorder['prices'],
                        'type'  =>  1,
                        'content'   =>  '收货订单交易',
                        'createtime'    =>  time(),
                        'arrivaltime'   =>  time(),
                        'status'    =>  1
                    ];
                    $re['s1'] = Db::name('reorder')->where('order_sn',$out_trade_no)->update(['status'=>2,'paytime'=>time(),'payway'=>$type]);
                    $re['s2'] = Db::name('account_log')->insert($ret1);
                    $send = new Send();
                    if ($reorder['order_user'] == 1) {
                        $goods = Db::name('receiving')->where('id',$reorder['goods_id'])->find();
                        $re['s3'] = $send->send($goods['mobile'],6);
                    } else {
                        $goods = Db::name('personal')->where('id',$reorder['uid'])->find();
                        $re['s4'] = $send->send($goods['mobile'],9);
                    }
                }
    		    error_log(date("Y-m-d H:i:s",time())."支付宝商城支付流程操作完成",3,'alipay_notify.log');
    		}else{
    		    $order = db::name('order')->where('order_sn',$out_trade_no)->find();
    		
        		if($order['status'] != 1){
        		    echo 'SUCCESS';die;
        		}
                $auth_group = DB::name("auth_group")->where(['name'=>['in',['投诉咨询','一级客服']]])->column('id');
                $auth_group_access = DB::name("auth_group_access")->where(['group_id'=>['in',$auth_group]])->column("uid");
                $admin_id = Db::name('admin')->where(['status'=>'normal','id'=>['in',$auth_group_access]])->orderRaw('Rand()')->value('id');
        		$goods = Db::name('goods')->where('id',$order['goods_id'])->find();
    
    
                $user = Db::name('personal')->where('id',$order['buyid'])->value('switch');
                error_log(date("Y-m-d H:i:s",time())."支付宝普通订单支付",3,'alipay_notify.log');
                if ($user == 2) {
                    $ret1 = [
                        'uid'   =>  $order['buyid'],
                        'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                        'money' =>  '-'.$order['amount'],
                        'type'  =>  1,
                        'content'   =>  '消费',
                        'createtime'    =>  time(),
                        'arrivaltime'   =>  time(),
                        'status'    =>  1
                    ];
                    $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>30,'paytime'=>time(),'payway'=>$type]);
                    $re['s2'] = Db::name('account_log')->insert($ret1);
                } else {
                    if ($goods['goods_class_type'] == 1) {
                        $ret1 = [
                            'uid'   =>  $order['buyid'],
                            'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                            'money' =>  '-'.$order['amount'],
                            'type'  =>  1,
                            'content'   =>  '消费',
                            'createtime'    =>  time(),
                            'arrivaltime'   =>  time(),
                            'status'    =>  1
                        ];
                        $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>11,'paytime'=>time(),'payway'=>$type]);
                        $re['s2'] = Db::name('account_log')->insert($ret1);
                        $easy = new Goeasy();
                        $msg = '您有待验证的订单了!';
                        $re['s5'] = $easy->sendToAdmin($admin_id,$msg);
                    } else {
                        $ret1 = [
                            'uid'   =>  $order['buyid'],
                            'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                            'money' =>  '-'.$order['amount'],
                            'type'  =>  1,
                            'content'   =>  '消费',
                            'createtime'    =>  time(),
                            'arrivaltime'   =>  time(),
                            'status'    =>  1
                        ];
                        //                $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>2,'paytime'=>time(),'payway'=>$type]);
                        if ($goods['method'] == 3) {
                            $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>5,'paytime'=>time(),'payway'=>$type]);
                        } else {
                            $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>2,'paytime'=>time(),'payway'=>$type]);
                        }
                        $re['s2'] = Db::name('account_log')->insert($ret1);
                        $send = new Send();
                        $re['s3'] = $send->send($goods['mobile'],2);
                        $easy = new Goeasy();
                        $msg = '您有待发货的订单了!';
                        $re['s5'] = $easy->sendToAdmin($admin_id,$msg);
                    }
                }
                error_log(date("Y-m-d H:i:s",time())."支付宝普通订单支付流程完成",3,'alipay_notify.log');
    		}
	    }
	    
	    echo 'SUCCESS';die;
	    
	}
	
	//重写回调处理函数
	/**
	 * @param WxPayNotifyResults $data 回调解释出的参数
	 * @param WxPayConfigInterface $config
	 * @param string $msg 如果回调处理失败，可以将错误信息输出到该方法
	 * @return true回调出来完成不需要继续回调，false回调处理未完成需要继续回调
	 */
	public function NotifyProcess()
	{
	    //TODO 用户基础该类之后需要重写该方法，成功的时候返回true，失败返回false
		$data['out_trade_no'] = 'jsapiI202203175661670392001000';
		$out_trade_no = substr($data['out_trade_no'],5);
		$type = '微信';
		if($out_trade_no[0] == "I"){
		    //商城订单
		    $reorder = Db::name('reorder')->where('order_sn',$out_trade_no)->find();
            $ret1 = [
                'uid'   =>  $reorder['buyid'],
                'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                'money' =>  '-'.$reorder['price'],
                'type'  =>  1,
                'content'   =>  '收货订单交易',
                'createtime'    =>  time(),
                'arrivaltime'   =>  time(),
                'status'    =>  1
            ];
            $re['s1'] = Db::name('reorder')->where('order_sn',$out_trade_no)->update(['status'=>2,'paytime'=>time(),'payway'=>$type]);
            $re['s2'] = Db::name('account_log')->insert($ret1);
            $send = new Send();
            if ($reorder['order_user'] == 1) {
                $goods = Db::name('receiving')->where('id',$reorder['goods_id'])->find();
                $re['s3'] = $send->send($goods['mobile'],6);
            } else {
                $goods = Db::name('personal')->where('id',$reorder['uid'])->find();
                $re['s4'] = $send->send($goods['mobile'],9);
            }
            echo 'sssss';die;
		}else{
		    $order = db::name('order')->where('order_sn',$out_trade_no)->find();
    		if($order['status'] != 1){
    		    echo 'success';die;
    		}
    		error_log('order info-----------'.json_encode($order),3,'vxpay1.log');
    		$goods = Db::name('goods')->where('id',$order['goods_id'])->find();
    		
            $auth_group = DB::name("auth_group")->where(['name'=>['in',['投诉咨询','一级客服']]])->column('id');
            $auth_group_access = DB::name("auth_group_access")->where(['group_id'=>['in',$auth_group]])->column("uid");
            $admin_id = Db::name('admin')->where(['status'=>'normal','id'=>['in',$auth_group_access]])->orderRaw('Rand()')->value('id');
    		if ($goods['goods_class_type'] == 1) {
                    $ret1 = [
                        'uid'   =>  $order['buyid'],
                        'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                        'money' =>  '-'.$order['amount'],
                        'type'  =>  1,
                        'content'   =>  '消费',
                        'createtime'    =>  time(),
                        'arrivaltime'   =>  time(),
                        'status'    =>  1
                    ];
                    $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>11,'paytime'=>time(),'payway'=>$type]);
                    
                    $re['s2'] = Db::name('account_log')->insert($ret1);
                    $easy = new Goeasy();
                    $msg = '您有待验证的订单了!';
                    $re['s5'] = $easy->sendToAdmin($admin_id,$msg);
                } else {
    		        error_log("金币交易",3,'vxpay1.log');
                    $ret1 = [
                        'uid'   =>  $order['buyid'],
                        'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                        'money' =>  '-'.$order['amount'],
                        'type'  =>  1,
                        'content'   =>  '消费',
                        'createtime'    =>  time(),
                        'arrivaltime'   =>  time(),
                        'status'    =>  1
                    ];
    //                $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>2,'paytime'=>time(),'payway'=>$type]);
    	            if ($goods['method'] == 3) {
    		            $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>5,'paytime'=>time(),'payway'=>$type]);
    	            } else {
    		            $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>2,'paytime'=>time(),'payway'=>$type]);
    	            }
                    $re['s2'] = Db::name('account_log')->insert($ret1);
                    $send = new Send();
                    $re['s3'] = $send->send($goods['mobile'],2);
                    $easy = new Goeasy();
                    $msg = '您有待发货的订单了!';
                    $re['s5'] = $easy->sendToAdmin($admin_id,$msg);
                }
		}
		
		
		echo 'success';
	}
}

